package com.middlegroup.subjectpay.config;

import com.middlegroup.common.exception.BusinessException;
import com.middlegroup.common.model.ResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartException;

import javax.servlet.http.HttpServletResponse;

/**
 * ClassName:GrobalExceptionHandler <br/>
 *
 * @author pc
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Throwable.class)
    @ResponseBody
    public ResponseEntity jsonErrorHandler(Exception e, HttpServletResponse rep) throws Exception {
        log.error("出错啦", e);
        String msg = "系统出错，请联系管理员!";
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
            rep.setStatus(400);
            return new ResponseEntity(ResponseEntity.STATUS_FAIL,null,msg,null);
        } else if (e instanceof BusinessException) {
            BusinessException exception = (BusinessException) e;
            //rep.setStatus(exception.getCode());
            return new ResponseEntity(ResponseEntity.STATUS_OK,null,exception.getMessage(),null);
        } else if (e instanceof IllegalArgumentException) {
            IllegalArgumentException exception = (IllegalArgumentException) e;
            //rep.setStatus(HttpStatus.BAD_REQUEST.value());
            return new ResponseEntity(ResponseEntity.STATUS_OK,null,exception.getMessage(),null);
        } else if (e instanceof MultipartException) {
            //rep.setStatus(HttpStatus.BAD_REQUEST.value());
            return new ResponseEntity(ResponseEntity.STATUS_OK,null,"图片大小不能超过3M",null);
        }else if (e instanceof BindException){
            BindException bindException = (BindException) e;
            StringBuffer sb  = new StringBuffer();
            for (FieldError fieldErro : bindException.getBindingResult().getFieldErrors()) {
                sb.append("【" + fieldErro.getField() + ":" + fieldErro.getDefaultMessage() + "】") ;
            }
            msg = sb.toString();
            return new ResponseEntity(ResponseEntity.STATUS_FAIL,null,msg,null);
        }
        return new ResponseEntity(ResponseEntity.STATUS_OK,null,msg,null);
    }

}
